package cn.zzuzhm.transaction.tx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import exception.BookStockException;
import exception.UserBalanceException;

@Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao {

	@Autowired 
	private JdbcTemplate jdbcTemplate;

	@Override
	public double findBookPriceByBid(String bid) {
		String sql = "SELECT price FROM book WHERE bid = ?";
		return jdbcTemplate.queryForObject(sql, Double.class, bid);
	}

	@Override
	public void updateBookStock(String bsid) {
		//检查库存是否充足，若不足，则抛出异常
		String sql2 = "SELECT stock FROM book_stock WHERE bsid = ?";
		int stock = jdbcTemplate.queryForObject(sql2, Integer.class, bsid);
		if(stock <= 0){
			throw new BookStockException("库存不足");
		}
		String sql = "UPDATE book_stock SET stock = stock - 1  WHERE bsid = ?";
	    jdbcTemplate.update(sql, bsid);
	}

	@Override
	public void updateUserAccount(int id, Double price) {
		//检查账户余额是否充足，若不足，则抛出异常
		String sql2 = "SELECT balance FROM user WHERE id = ?";
		double balance = jdbcTemplate.queryForObject(sql2, Double.class, id);
		if(balance < price){
			throw new UserBalanceException("账户余额不足");
		}
		String sql = "UPDATE user SET balance = balance - ? where id = ?";
		jdbcTemplate.update(sql, price,id);		
	}

	

}
